%this is spatial median filtering
clc;
clear all;
close all;

A = imread('tire.tif');
imshow(A);
title('Original Image');
A = imnoise(A,'salt & pepper',0.02);
% [m,n]= size(A);
A = double(A);


% for i = 1:m
%     for j = 1:n
%         if(i==1 || j==1 || i == m || j == n)
%             A(i,j) =0;
%         end
%     end
% end

A = padarray(A,[1,1]);

[m,n]= size(A);
B = zeros(m,n);

for i = 2:m-2
    for j = 2:n-2
        C = ([A(i-1,j-1) A(i-1,j) A(i-1,j+1);(A(i,j-1)) (A(i,j)) (A(i,j+1)); A(i+1,j-1) A(i+1,j) A(i+1,j+1)]);
%         D = C*mask;
        A1 = (A(:));
        A1 = sort(A1);
        B(i,j) = median(C(:));
%         B(i-1,j-1) = D(1,1);
%         B(i-1,j) = D(1,2);
%         B(i-1,j+1) = D(1,3);
%         B(i,j-1) = D(2,1);
%         B(i,j) = D(2,2);
%         B(i,j+1) = D(2,3);
%         B(i+1,j-1) = D(3,1);
%         B(i+1,j)= D(3,2);
%         B(i+1,j+1) = D(3,3);
    end
end

title('Modified Image');
% figure,imshow(uint8(B));
imshowpair(uint8(A),uint8(B),'montage')